package com.cloud.common.akka;

import com.cloud.common.bean.SessionInfo;
import com.cloud.common.context.SessionContext;
import com.cloud.common.context.TraceContext;
import com.cloud.common.context.VersionContext;

import java.util.UUID;
import java.util.concurrent.CountDownLatch;

public class ActorMessage<T> {

    private T data;

    // 批次ID
    String batchId;
    // 多个Actor协调参数
    CountDownLatch countDownLatch;
    boolean completed;

    // 上下文参数
    String traceId;
    String version;
    SessionInfo sessionInfo;

    public ActorMessage(T data) {
        this.data = data;
        this.batchId = UUID.randomUUID().toString();
        this.traceId = TraceContext.get();
        this.version = VersionContext.get();
        this.sessionInfo = SessionContext.get();
    }

    public ActorMessage(T data, int latchCount) {
        this(data);
        if (latchCount > 0) {
            this.countDownLatch = new CountDownLatch(latchCount);
        }
    }

    public T getData() {
        return data;
    }

    public String getBatchId() {
        return batchId;
    }

    public boolean finished() {
        if (countDownLatch == null) {
            return false;
        }
        if (completed && countDownLatch.getCount() > 0) {
            countDownLatch.countDown();
        }
        return countDownLatch.getCount() == 0;
    }

}
